#include <GyverMAX6675.h>
#include "SSD1306Wire.h"

#define DATA_PIN  6  // SO
#define CS_PIN    7  // CS
#define CLK_PIN   8  // SCK
#define SDA_PIN 9
#define SCL_PIN 10

#define JDQ_PIN 3

//#define MAX6675_DELAY 10

GyverMAX6675<CLK_PIN, DATA_PIN, CS_PIN> sens;

SSD1306Wire display(0x3c, SDA_PIN, SCL_PIN);

unsigned int MAX_TEMP = 250;
unsigned int targetTemp = 200;

unsigned int FIRST_POS_X = 30;
unsigned int SECOND_POS_X = 100;

void setup() {
  Serial.begin(115200);
  analogReadResolution(8);
  display.init();
  display.flipScreenVertically();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  // gpio 3 继电器
  pinMode(JDQ_PIN, OUTPUT);
}

void loop() {
  // 读取设置的温度
  targetTemp = analogRead(4); // 4号引脚连接温度传感器

  // 展示温度信息
  display.clear();
  display.setFont(ArialMT_Plain_16);
  display.drawString(FIRST_POS_X, 5, "current");
  display.drawString(SECOND_POS_X, 5, "target");
  display.drawHorizontalLine(0, 28, 128);
  if (sens.readTemp()) {
    //Serial.print("Temp: ");
    //Serial.print(sens.getTemp());
    //Serial.print(sens.getTempInt());
    //Serial.println(" *C");
    display.setFont(ArialMT_Plain_24); // set font size
    int temp = sens.getTempInt();
    // 根据温度控制继电器
    if (temp < targetTemp) {
      digitalWrite(JDQ_PIN, 1);
    } else {
      digitalWrite(JDQ_PIN, 0);
    }
    display.drawString(FIRST_POS_X, 36, String(temp) + "C");
    display.drawString(SECOND_POS_X, 36, String(targetTemp) + "C"); // draw temperature string
  } else {
    //Serial.println("Error");
    display.drawString(FIRST_POS_X, 36, "Error");
  }
  display.display();
  delay(1000);
}